const toString = Object.prototype.toString;
// 定义is方法
function is(val: unknown, type: string) {
	return toString.call(val) === `[object ${type}]`;
}

function isString(val: unknown): val is string {
	return is(val, 'String');
}

function isNumber(val: unknown): val is number {
	return is(val, 'Number');
}

function isBoolean(val: unknown): val is boolean {
	return is(val, 'Boolean');
}

function isUndefined<T = unknown>(val?: T): val is T {
	return typeof val === 'undefined';
}

function isNull(val: unknown): val is null {
	return val === null;
}

function isObject(val: any): val is Record<any, any> {
	return val !== null && is(val, 'Object');
}
function isFunction(val: unknown): val is Function {
	return typeof val === 'function';
}
function isArray(val: any): val is Array<any> {
	return val && Array.isArray(val);
}
function isDate(val: unknown): val is Date {
	return is(val, 'Date');
}

function isRegExp(val: unknown): val is RegExp {
	return is(val, 'RegExp');
}
function isMap(val: unknown): val is Map<any, any> {
	return is(val, 'Map');
}
function isPromise<T = any>(val: any): val is Promise<T> {
	return is(val, 'Promise') && isFunction(val.then) && isFunction(val.catch);
}
function isJsonObjectString(val: string): val is string {
	if (!val) {
		return false;
	}
	return val.startsWith('{') && val.endsWith('}');
}
function isWindow(val: any): val is Window {
	return typeof window !== 'undefined' && is(val, 'Window');
}
function isElement(val: unknown): val is Element {
	return isObject(val) && !!val.tagName;
}
function isUrl(path: string): boolean {
	const reg = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/;
	return reg.test(path);
}
function isEmpty<T = unknown>(val: T): val is T {
	if (isArray(val) || isString(val)) {
		return val.length === 0;
	}

	if (val instanceof Map || val instanceof Set) {
		return val.size === 0;
	}

	if (isObject(val)) {
		return Object.keys(val).length === 0;
	}

	return false;
}

export {
	is,
	isString,
	isNumber,
	isBoolean,
	isNull,
	isUndefined,
	isObject,
	isFunction,
	isArray,
	isDate,
	isRegExp,
	isMap,
	isPromise,
	isJsonObjectString,
	isWindow,
	isElement,
	isUrl,
	isEmpty,
};
